package com.baichuan.util;

import com.baichuan.entity.AppUser;
import lombok.extern.slf4j.Slf4j;

/**
 * 小程序用户token工具
 *
 * @author leo
 * @version 1.0
 * @date 2020年4月3日
 */
@Slf4j
public class AppletUserTokenUtil {
    //token有期时长1天
    private static long TOKEN_VALIDITY = 1000l * 60 * 60 * 24 * 365;

    private static String SPACE = "_#_";

    /**
     * 验证token合法性，token组成：时间戳 + "_#_" + openId + "_#_" + 用户id + "_#_" + 车商id + "_#_" + 客户经理id
     *
     * @param token
     * @return
     */
    public static boolean isVerifyToken(String token) {
        if (StringUtils.isEmpty(token))
            return false;
        try {
            String decryptedStr = SimpleEncrypt.decrypt(token);
            String[] arr = decryptedStr.split(SPACE);
            if (arr.length != 5)
                return false;
            // //时间戳timestamp
            String timestamp1 = arr[0];
            /*// openId
            String openId = arr[1];
            // userId
            String userId = arr[2];
            // dealerId
            String dealerId = arr[3];
            //客户经理id custMagerId
            String custMagerId = arr[4];*/
            if (System.currentTimeMillis() - Long.parseLong(timestamp1) > TOKEN_VALIDITY)
                return false;
            return true;
        } catch (Exception e) {
            log.error("token:{}解密token失败，错误信息为{}", token, e.getMessage());
            return false;
        }
    }

    /**
     * 生成token, token组成：时间戳 + "_#_" + openId + "_#_" + 用户id + "_#_" + 车商id + "_#_" + 客户经理id
     * @param openId
     * @param userId
     * @param dealerId
     * @param custMagerId
     * @return
     */
    public static String getToken(String openId, Integer userId, Integer dealerId, Integer custMagerId) {
        if (userId == null)
            userId = -1;
        if (dealerId == null)
            dealerId = -1;
        if (custMagerId == null)
            custMagerId = -1;
        long currentTimeMillis = System.currentTimeMillis();
        String encryptStr = currentTimeMillis + SPACE + openId + SPACE + userId + SPACE + dealerId + SPACE + custMagerId;
        return SimpleEncrypt.encrypt(encryptStr);
    }

    public static String getOpenId(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            return arr[1];
        } catch (Exception e) {
            log.error("getOpenId token:{}", token, e);
        }
        return null;
    }

    public static Integer getUserId(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            return Integer.parseInt(arr[2]);
        } catch (Exception e) {
            log.error("getUserId token:{}", token, e);
        }
        return null;
    }

    public static Integer getDealerId(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            return Integer.parseInt(arr[3]);
        } catch (Exception e) {
            log.error("getDealerId token:{}", token, e);
        }
        return null;
    }

    public static Integer getCustMagerId(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            String custMagerId = arr[4];
            if ("-1".equals(custMagerId))
                return null;
            return Integer.parseInt(custMagerId);
        } catch (Exception e) {
            log.error("getCustMagerId token:{}", token, e);
        }
        return null;
    }

    public static AppUser getUser(String token) {
        if (token == null || "".equals(token))
            return null;
        try {
            String str = SimpleEncrypt.decrypt(token);
            String[] arr = str.split(SPACE);
            AppUser appUser = new AppUser();
            appUser.setOpenId(arr[1]);
            appUser.setBindUserId(Integer.parseInt(arr[2]));
            appUser.setBindDealerId(Integer.parseInt(arr[3]));

            String custMagerId = arr[4];
            if (!"-1".equals(custMagerId))
                appUser.setCustMagerId(Integer.parseInt(custMagerId));
            return appUser;
        } catch (Exception e) {
            log.error("getDealerId token:{}", token, e);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getToken("oZ8DE4p7gQ3XgeemR3dX81A2rW3c", 1, 100000, 5));
        System.out.println(getToken("oZ8DE4gKu7iaBDQ7xDvNc0I4WkdE", 5, 100000, -1));

        System.out.println(getToken("oZ8DE4kz7znyGVnoj7GcWCVMsbLA", 89, 100000, 9));

        System.out.println(getToken("oZ8DE4uNKQxWIVg19-gZBhtCo3f0", 92, 100026, null));
    }
}
